#import Initialisation, InterfaceRecovery, sys
import sys, re, InterfaceRB, os, Initialisation

#TODO



#DONE

#create feature to save a set of items from a dict into xml file
#create feature to add new items to an existing xml file on the fly (no loss)
#create feature to read xml files and extract only 1 key
#add cli core control
#Create tests
#handle IO exceptions
#create feature to parse whole xml file and return all keys
#get last time of modification
#save last time of backup in an xml file
#retreive last time of backup in xml file
#compare files times
#create temporary xml file containing files to backup
#create interface to xdelta
#make it dynamic with temporary xml file
#create delta files with time of backup
#create a feature to create all necessary hierarchy and files for app to work
#create a feature that check that all files exist or relaunch creation
#create an interface with Xdelta retreiving on the fly the directories and files to save
#be able to choose the level of compression of the delta
#create an interface to recover the file from a specific date
#create interface to setACL for backup
#create interface to setACL for recovery
#reorganize code structure
#daemon task scheduler
#Test != threading interface (opipe,spawn)
#Add comments
#finish monthly cleanup routine

def listing(argList):
    """Check arguments for listing"""
    
    if len(argList)<2:
        print 'Missing argument "filename" for listing -l'
    else:
        list=InterfaceRB.getTimesToRecover(argList[-1])
        if len(list)<1:
            print 'File %s does not exist in backup' % argList[-1]
        for element in list:
            print element

def recover(argList):
    """Check arguments for recovery & launch it"""
    
    # can be -r pathtorecover = restore everything from last backup into path
    #        -r name;name2;name3 pathtorecover = restore names from last backup into path
    #        -r name date path = restore given name at given date into path
    
    if len(argList)<2:
        print 'Missing argument, "recoveryPath" is neccessary for recovery'
    else:
        if len(argList)==2:
            if os.path.exists(arg[1]):
                InterfaceRB.Recover(argList[1])
            else:
                print 'path of recovery does not exist'
        if len(argList)==3:
            list=argList[1].split(';')
            if os.path.exists(argList[-1]):
                InterfaceRB.Recover(argList[-1],list)
            else:
                print 'path of recovery does not exist'
        if len(argList)==4:
            list=[]
            list.append(argList[1])
            if os.path.exists(argList[-1]):
                InterfaceRB.Recover(argList[-1],list,date)
            else:
                print 'path of recovery does not exist'
    
def add(argList):
    """Check arguments & add them to backup"""
    
    # can be -add path1;path2;path3
    #        -add path
    if len(argList)<2:
        print 'Missing argument, "PathToFile" is neccessary for adding it to backup'
    else:
        list=argList[1].split(';')
        boolean=False
        for elements in list:
            if not os.path.exists(elements):
                boolean=True
        if boolean:
            print 'One of the paths does not exist or is erroneous for adding it to backup'
        else:
            InterfaceRB.AddToBackup(list)
    
def help(argList):
    """Display help for CLI"""
    
    print ' '
    print 'EBT stands for Easy Backup Tool:'
    print ' '
    print '-l name = lists of backups available for particular filename'
    print '-r pathToRecovery = restore everything from last backup into path'
    print    '-r name;name2;name3 pathToRecovery = restore names from last backup into path'
    print    '-r name date path = restore given name at given date into path'
    print '-add path;anotherpath;... = add new files to backup // ONLY ABSOLUTE PATHS'
    print '-help = gives the command help'
    

if __name__ == "__main__":
    """ Launch entire program and retrieve arguments for CLI """
    
    #CLI: -l "name" =lists of backups for particular name,
    #     -r "name" "date" "recoverypath"= recover filename at date in recoverypath
    #     -add "path;anotherpath;..."= add new files toSelect backup // ONLY ABSOLUTE PATHS
    #     -help = gives the command help
    
    Initialisation.Check_and_retrieve()
    paths = Initialisation.__retrieveInfo()
    
    actions={
             '-l': listing,
             '-r': recover,
             '-add': add,
             '-help': help}
    
    arg= sys.argv[1:]
    if len(arg)<1 :
        print '"EBT" takes at least one argument, %d were given. Type -help for more information' % len(arg)
    else:
        pattern = '^-(l|r|add|help)$'
        if (re.search(pattern, arg[0])):
            actions.get(arg[0])(arg)
        else:
            print 'Unknown argument for "EBT". Type -help for more information'
